package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.Utils.PageUtil;
import com.example.haoqisystem.entity.TrainningApplication;
import com.example.haoqisystem.request.CreateTrainningApplicationRequest;
import com.example.haoqisystem.request.QueryTrainningApplicationListrequest;
import com.example.haoqisystem.request.UpdateTrainningApplicationRequest;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.response.PageResult;
import com.example.haoqisystem.respository.TrainningApplicationRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TrainningApplicationService {
    private final TrainningApplicationRepository trainningApplicationRepository;
    //新建培训申请
    public BaseResponse<TrainningApplication> add(CreateTrainningApplicationRequest request) {
        try{
            TrainningApplication application=new TrainningApplication();
            BeanUtil.copyProperties(request,application, CopyOptions.create().setIgnoreNullValue(true));
            //是否产生培训计划，刚创建时要设置为false
            application.setIsGeneratePlan(false);
            TrainningApplication application1=trainningApplicationRepository.save(application);
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS,true,application1);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //查看培训申请详情
    public BaseResponse<TrainningApplication> detail(Long id,boolean deleted) {
        try{
            Specification<TrainningApplication> specification=(root, query, builder) -> {
                List<Predicate> predicates=new ArrayList<>();
                predicates.add(builder.equal(root.get("id"), id));
                predicates.add(builder.equal(root.get("deleted"),deleted));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            Optional<TrainningApplication> application=trainningApplicationRepository.findOne(specification);
            if (!application.isPresent()){
                return new BaseResponse<>("该申请不存在！",false,null);
            }
            TrainningApplication application1=application.get();
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,application1);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //培训申请分页列表查询
    public BaseResponse<PageResult<TrainningApplication>> queryList(QueryTrainningApplicationListrequest request) {
        try{
            Specification<TrainningApplication> specification=(root, query, builder) -> {
                List<Predicate>predicates=new ArrayList<>();
                if(request.getApplicationCompany()!=null&&!request.getApplicationCompany().equals("")){
                    String companyLike="%"+request.getApplicationCompany()+"%";
                    predicates.add(builder.like(root.get("applicationCompany"),companyLike));
                }
                if(request.getTimeBetween()!=null&&!request.getTimeBetween().equals("")){
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date beginTime = null;
                    Date endTime = null;
                    try {
                        beginTime = dateFormat.parse(request.getTimeBetween().substring(0, 10));
                        endTime = dateFormat.parse(request.getTimeBetween().substring(13));
                    } catch (ParseException e) {
                        // 处理日期解析异常
                        e.printStackTrace(); // 或者记录日志
                    }
                    predicates.add(builder.between(root.get("applicationTime"),beginTime,endTime));
                }
                predicates.add(builder.equal(root.get("deleted"),request.isDeleted()));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<TrainningApplication> list=trainningApplicationRepository.findAll(specification);
            Collections.reverse(list);
            PageResult<TrainningApplication> page=PageUtil.getPage(
                    list,
                    request.getPageNum(),request.getPageSize());
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,page);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //删除培训申请id
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<String> delete(Long id) {
        if (id == null) {
            return new BaseResponse<>(ConstUtil.ERROR, false, "ids不能为空！");
        }
        Optional<TrainningApplication> optional=trainningApplicationRepository.findByIdAndDeletedFalse(id);
        if(!optional.isPresent()){
            return new BaseResponse<>("该申请不存在！",false,null);
        }
        TrainningApplication application=optional.get();
        application.setDeleted(true);
        trainningApplicationRepository.save(application);
        return new BaseResponse<>(ConstUtil.UPDATE_SUCESS, true, "删除成功！");
    }

    //查看培训申请列表
    public BaseResponse<List<TrainningApplication>> queryList1(String applicationCompany,
                                                               String timeBetween,
                                                               Boolean deleted,
                                                               Boolean isGeneratePlan,
                                                               String lectureName,
                                                               Long id) {
        try{
            Specification<TrainningApplication> specification=(root, query, builder) -> {
                List<Predicate>predicates=new ArrayList<>();
                if(applicationCompany!=null&&!applicationCompany.equals("")){
                    String companyLike="%"+applicationCompany+"%";
                    predicates.add(builder.like(root.get("applicationCompany"),companyLike));
                }
                if(timeBetween!=null&&!timeBetween.equals("")){
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date beginTime = null;
                    Date endTime = null;
                    try {
                        beginTime = dateFormat.parse(timeBetween.substring(0, 10));
                        endTime = dateFormat.parse(timeBetween.substring(13));
                    } catch (ParseException e) {
                        // 处理日期解析异常
                        e.printStackTrace(); // 或者记录日志
                    }
                    predicates.add(builder.between(root.get("applicationTime"),beginTime,endTime));
                }
                if(isGeneratePlan!=null){
                    predicates.add(builder.equal(root.get("isGeneratePlan"),isGeneratePlan));
                }
                if(lectureName!=null&&!lectureName.equals("")){
                    String nameLike="%"+lectureName+"%";
                    predicates.add(builder.like(root.get("lectureName"),nameLike));
                }
                if(id!=null&&!id.equals("")){
                    predicates.add(builder.equal(root.get("id"),id));
                }
                predicates.add(builder.equal(root.get("deleted"),deleted));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<TrainningApplication> list=trainningApplicationRepository.findAll(specification);
            Collections.reverse(list);
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS,true,list);
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //更新
    public BaseResponse<TrainningApplication> update(UpdateTrainningApplicationRequest request) {
        if(request.getId()==null||request.getId().equals("")){
            return new BaseResponse<>("需要培训申请id！",false,null);
        }
        try{
            Optional<TrainningApplication> optionalpplication=trainningApplicationRepository.findByIdAndDeletedFalse(request.getId());
            if(!optionalpplication.isPresent()){
                return new BaseResponse<>("该申请不存在！",false,null);
            }
            TrainningApplication application=optionalpplication.get();
            BeanUtil.copyProperties(request,application,CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,trainningApplicationRepository.save(application));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }
}
